 ///
 /// @file    Computer.cc
 /// @author  lemon(haohb13@gmail.com)
 /// @date    2023-04-20 18:05:03
 ///
 
#include <string.h>
#include <iostream>
using std::cout;
using std::endl;

class Computer
{//class的默认访问权限是private的
public:
	Computer(const char * brand, double price)
	: _brand(new char[strlen(brand) + 1]())
	, _price(price)
	{
		cout << "Computer(const char*, float)" << endl;
		strcpy(_brand, brand);
		_totalPrice += _price;
	}

	Computer(const Computer & rhs)
	: _brand(new char[strlen(rhs._brand) + 1]())
	, _price(rhs._price)
	{	
		cout << "Computer(const Computer&)" << endl;	
		strcpy(_brand, rhs._brand);
	}

	Computer & operator=(const Computer & rhs)
	{
		cout << "Computer & operator=(const Computer&)" << endl;
		if(this != &rhs) {//1. 自复制
			//2. 回收左操作的空间
			delete [] _brand;
			//3. 进行深拷贝
			_brand = new char[strlen(rhs._brand) + 1]();
			strcpy(_brand, rhs._brand);

			this->_price = rhs._price;
		}
		return *this;//4. return *this
	}

	void print();

	//没有this的指针
	static void printTotalPrice()
	{
		//cout << _brand << endl;//error
		//print();//error
		cout << "total price :" << _totalPrice << endl;
	}

	~Computer()
	{
		cout << "~Computer()" << endl;
		if(_brand) {
			//Safe delete操作
			delete [] _brand;
			_brand = nullptr;
		}
	}

private:
	char * _brand;
	double _price;
	static double _totalPrice;
};

//位于全局静态区, 在类之外进行初始化
double Computer::_totalPrice = 0;
 
void Computer::print() 
{
	cout << "brand:" << this->_brand << endl;
	cout << "price:" << this->_price << endl;
	cout << "total price:" << _totalPrice << endl;
}

void test0() 
{
	cout << "sizeof(Computer):" << sizeof(Computer) << endl;
	Computer pc("Xiaomi", 7777);
	cout << "pc:";
	pc.print();
	pc.printTotalPrice();
	//不需要跟某一个对象绑定在一起, 这是更常用的调用方式
	Computer::printTotalPrice();//直接通过类名进行调用

	Computer pc2("Huawei", 8888);
	cout << "pc2:";
	pc2.print();
	pc2.printTotalPrice();
	cout << endl;


} 
 
int main(void)
{
	test0();
	return 0;
}
